package com.wandousoushu.jiusen.wxapi

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.wandousoushu.jiusen.MainActivity
import com.wandousoushu.jiusen.MyApplication
import com.wandousoushu.jiusen.R
import com.wandousoushu.jiusen.bean.AdBean
import com.wandousoushu.jiusen.bean.H5AdBean
import com.wandousoushu.jiusen.bean.UserInfo
import com.wandousoushu.jiusen.booksource.data.entities.Book
import com.wandousoushu.jiusen.booksource.model.BookManager
import com.wandousoushu.jiusen.booksource.model.SearchBookManager
import com.wandousoushu.jiusen.util.GsonUtils
import com.wandousoushu.jiusen.util.NetworkUtil
import com.wandousoushu.jiusen.util.putPrefBoolean
import com.wandousoushu.jiusen.util.putPrefString
import com.wandousoushu.jiusen.web.http.MainHttpConsts
import com.wandousoushu.jiusen.web.http.MainHttpUtils
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.lang.ref.WeakReference
import java.util.*


class WXEntryActivity : AppCompatActivity() , IWXAPIEventHandler {

    private var api: IWXAPI? = null
    private var resp: BaseResp? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        api = WXAPIFactory.createWXAPI(this, MainHttpConsts.WX_APP_ID, true);
        api!!.handleIntent(getIntent(), this);

    }

    override fun onResp(resp: BaseResp?) {
        var result = ""
        if (resp != null) {
            this.resp = resp
        }
        when (resp!!.errCode) {
            BaseResp.ErrCode.ERR_OK -> {
                result = "发送成功"
                //Toast.makeText(this, result, Toast.LENGTH_LONG).show()
                val code = (resp as SendAuth.Resp).code
                Thread(Runnable { //向服务端发送请求,预计返回用户信息数据，返回给前端进行显示。
                    try{
                    val returnData=MainHttpUtils.getInstance().WeiXinLogin("",code,MyApplication.instance.wxLoginState)
                    if (returnData == null) {
                        mHandle.sendEmptyMessage(0)
                        return@Runnable
                    }
                    val jsonObject = JSONObject(returnData)
                    if (jsonObject.getInt("code") == 1) {
                        val data = jsonObject.getString("data")
                        if (!TextUtils.isEmpty(data)) {
                            val userInfo = GsonUtils.parseJObject(data, UserInfo::class.java)
                            if (userInfo != null&&MyApplication.instance.wxLoginState.equals(userInfo.wx_state)) {
                                MyApplication.instance.token = userInfo.token
                                MyApplication.instance.nickName = userInfo.user_nickname
                                MyApplication.instance.phoneNum = "微信用户"
                                MyApplication.instance.userId = userInfo.id
                                MyApplication.instance.isVip = if (userInfo.is_vip == 1) true else false
                                MyApplication.instance.userinfo = userInfo
                                MyApplication.instance.isLogin=true
                                MyApplication.instance.isWxUser=true
                                applicationContext.putPrefString("wxopenid",userInfo.openid)
                            } else {
                                mHandle.sendEmptyMessage(0)
                                return@Runnable
                            }
                        } else {
                            mHandle.sendEmptyMessage(0)
                            return@Runnable
                        }
                        mHandle.sendEmptyMessage(1)
                    } else {
                        val msg = Message.obtain()
                        msg.obj = jsonObject.getString("msg")
                        msg.what = 2
                        mHandle.sendMessage(msg)
                        finish()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                }).start()
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
                result = "发送取消"
                //Toast.makeText(this, result, Toast.LENGTH_LONG).show()
                finish()
            }
            BaseResp.ErrCode.ERR_AUTH_DENIED -> {
                result = "发送被拒绝"
                //Toast.makeText(this, result, Toast.LENGTH_LONG).show()
                finish()
            }
            else -> {
                result = "发送返回"
                //Toast.makeText(this, result, Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }

    override fun onReq(p0: BaseReq?) {
        api = WXAPIFactory.createWXAPI(this, MainHttpConsts.WX_APP_ID, false);
        api!!.handleIntent(getIntent(), this);
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        api!!.handleIntent(intent, this)
    }

    private fun HttpGetSearckKey() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetSearchKeys(MyApplication.instance.token)
                        ?: return@Runnable
                val jsonObject = JSONObject(returnData)
                if (jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) {
                        return@Runnable
                    }
                    val historyKeys = GsonUtils.parseJArray(data, String::class.java)
                    SearchBookManager.GetInstance().AddHistoryKeys(historyKeys)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetBookMark() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetBooks(1, MyApplication.instance.token) ?: return@Runnable
                val jsonObject = JSONObject(returnData)
                if (jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    val jObject = JSONObject(data)
                    val lists = jObject.getString("lists")
                    val jsonArray = JSONArray(lists)
                    for (i in 0 until jsonArray.length()) {
                        val json = jsonArray[i] as JSONObject
                        val book = Book()
                        book.name = json.getString("name")
                        book.bookUrl = json.getString("url")
                        book.tocUrl = json.getString("chapter_url")
                        book.latestChapterTitle = json.getString("final_refresh_data")
                        book.coverUrl = json.getString("cover_url")
                        book.author = json.getString("author")
                        book.intro = json.getString("introduce")
                        book.origin = json.getString("origin")
                        book.originName = json.getString("origin_name")
                        book.charset = json.getString("charset")
                        book.group = 1
                        book.durChapterTitle = json.getString("dur_chapter_title")
                        book.durChapterIndex = json.getInt("dur_chapter_index")
                        book.durChapterPos = json.getInt("dur_chapter_pos")
                        book.order=i
                        BookManager.GetInstance().AddBook(book)
                    }
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetPageAd() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetPageViewAdH5()
                if (returnData == null) {
                    return@Runnable
                }
                val jsonObject = JSONObject(returnData)
                if (jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    MyApplication.instance.pageH5=GsonUtils.parseJObject(jsonObject.getString("data"), H5AdBean::class.java)
                    //MyApplication.instance.pageAdList = GsonUtils.parseJArray(jsonObject.getString("data"), AdBean::class.java)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private val mHandle: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0 -> {
                    Toast.makeText(applicationContext, resources.getString(R.string.login_http_fail), Toast.LENGTH_SHORT).show()
                    finish()
                }
                1 -> {
                    HttpGetSearckKey()
                    HttpGetBookMark()
                    HttpGetPageAd()
                    val intent = Intent(applicationContext, MainActivity::class.java)
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                }
                2 -> Toast.makeText(applicationContext, msg.obj.toString(), Toast.LENGTH_SHORT).show()
            }
        }
    }
}